﻿using System;

namespace RexToy.UI.Controls
{
    public class ListView : Container
    {
        private ListViewItem __clickedItem;
        public ListViewItem ClickedItem
        {
            get { return __clickedItem; }
        }

        public string[] events = new string[] { "onitemclick" };

        public ListView()
        {
            __sizeUpdate = false;
            this.__domNode = RexToy.UI.Controls.DomNode.Create(new DomNodeCreateOptions()
            {
                tag = Tag.Ul,
                hashName = "container",
                className = "ui-listview ui-listview-inset ui-corner-all ui-shadow"
            });
        }

        private void ClickItem(ListViewItem clickedItem)
        {
            this.__clickedItem = clickedItem;
            this.__FireEvent("onitemclick");
        }

        public void AppendItem(ListViewItem listItem)
        {
            if (listItem.Clickable)
            {
                listItem.AttachEvent("onclick", new Action<ListViewItem>(this.ClickItem).Bind(this));
            }

            this.AppendControl(listItem);
            this.AdjustCorner();
        }

        public void RemoveItem(ListViewItem listItem)
        {
            this.RemoveControl(listItem);
            this.AdjustCorner();
        }

        public void InsertItemAt(ListViewItem listItem, uint index)
        {
            if (listItem.Clickable)
            {
                listItem.AttachEvent("onclick", new Action<ListViewItem>(this.ClickItem).Bind(this));
            }

            this.InsertControlAt(listItem, index);
            this.AdjustCorner();
        }

        private void AdjustCorner()
        {
            if (this.__controls.Length == 0) return;

            for (var i = 0; i < this.__controls.Length; i++)
            {
                var dom = this.__controls[i].DomNode;
                dom.RemoveClass("ui-corner-top");
                dom.RemoveClass("ui-corner-bottom");
            }

            var first = this.__controls[0].DomNode;
            first.AppendClass("ui-corner-top");
            var last = this.__controls[this.__controls.Length - 1].DomNode;
            last.AppendClass("ui-corner-bottom");
        }

        public void ClearItems()
        {
            this.ClearControls();
        }
    }
}
